package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

@SuppressWarnings("serial")
public class CheckRegServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		response.setContentType("text/html");
		HttpSession session = request.getSession();
		DBObject dbObject = (DBObject) session.getAttribute("users");
		if(dbObject==null)
		{
			try {
				response.getWriter().println("<script>window.location='http://hatforrent.com/login'</script>");
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		response.setContentType("text/html");
		String sitemap = request.getParameter("sitemap");
		String type = request.getParameter("type");
		
		DBCollection collection = Data.data("urlCraw");
		
		DBCursor cursor = collection.find(new BasicDBObject("domain",Utils.fomatDmain(sitemap)).append("type", type)).limit(10);

		if(cursor.size()>0)
		{
			ArrayList<DBObject> list = Utils.returnCursor(cursor);
			
			request.setAttribute("list", list);
		} else {
			DBCollection coll = Data.data("saveReg");
			cursor=coll.find(new BasicDBObject("domain",Utils.fomatDmain(sitemap)));
			ArrayList<DBObject> list = Utils.returnCursor(cursor);
			
			request.setAttribute("list", list);
		}
		if(cursor.size()<=0)
		{
			response.getWriter().println("Currently you are the first to get your news from this site.");
		} else {
			try {
				request.getRequestDispatcher("/check_reg.jsp").forward(request, response);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
	}
}
